/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Clases;


import Frames.PANEL;
import com.mysql.jdbc.Connection;
import java.io.*;
import java.net.URLDecoder;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;



/**
 *
 * @author usuario
 */
public class Conexion {
    
    Clases.Encriptacion Encrypt = new Clases.Encriptacion();    
    public static String host_ip = "";
    public static String user = "";
    public static String pass = "";
    public static String bd = "";
    public static Connection conn = null;
    public static Statement st;
    public static ResultSet rs;
  
    private static Logger log = Logger.getLogger(Conexion.class);
    
    
    public String getBd() {
        return bd;
    }

    public String getHost_ip() {
        return host_ip;
    }

    public String getPass() {
        return pass;
    }

    public String getUser() {
        return user;
    }
    
    
    
    
    public boolean conect() throws SQLException{       
        boolean exito=false;
        try {
            SetConfig ();           
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "No se Encuentra el Archivo de Configuración ..");
            log.error(ex);
        }
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = (Connection) DriverManager.getConnection("jdbc:mysql://"+host_ip+"/"+bd,user,pass);                
            st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
            //st.setPoolable(true);
            //conn.setAutoReconnect(true);
            exito = true;        
        } catch (ClassNotFoundException ex) {
            log.error(ex);
        }
        
        return exito;
    }
    
    
    
    /*
    public boolean desconectar() throws SQLException{        
        rs.close();        
        return true;
    }
    */
        
    public boolean sentencia (String sql) {
        boolean comp=false;
        rs = null;        
        try {
            rs = st.executeQuery(sql);
            if(rs.next()){
                comp=true;
            }  
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
            log.error(ex);
        }
             
        return comp;
    }
    
    public boolean sentenciaupdate (String sql){
        boolean comp=false;
        try {
            st.executeUpdate(sql);            
            comp = true;
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
            log.error(ex);
        }
        return comp;
    }
    
    
    public void SetConfigTXT () throws IOException{
        String path = new File("config").getAbsolutePath()+"\\datos.txt";  
        System.out.println(path);
        String list [] = new String [5];
        int i = 0;
        File archivo = null;
        FileReader fr = null;
        BufferedReader br = null;
        archivo = new File (path);
        try {
            fr = new FileReader (archivo);
        } catch (FileNotFoundException ex) {
            log.error(ex);
        }
        br = new BufferedReader(fr);

         // Lectura del fichero
        String linea;
        try {
            while((linea=br.readLine())!=null){
                list[i] = Encrypt.DecryptBase64(linea);
                i++;
            }                
        } catch (IOException ex) {
            log.error(ex);
        } 
        
        Conexion.host_ip = list[0];
        Conexion.user = list[1];
        Conexion.pass = list[2];  
        Conexion.bd = list[3];
        
    }
    
    private void SetConfig() throws IOException{
        FileInputStream in = null;       
        Properties prop = new Properties();    
        in = this.getFileFromRouteDeveloper();
        //in = new java.io.FileInputStream(this.getFileFromRoute());
        
        if (in != null) {
            prop.load(in);
            if (prop != null) {             
                Conexion.host_ip = Encrypt.DecryptBase64(prop.getProperty("servidor", "").trim());
                Conexion.user = Encrypt.DecryptBase64(prop.getProperty("usuario", "").trim());
                Conexion.pass = Encrypt.DecryptBase64(prop.getProperty("password", "").trim());  
                Conexion.bd = Encrypt.DecryptBase64(prop.getProperty("base", "").trim());
            }
        }
        log.info("Seteo de Paramteros Correcto");
    }
    
    private File getFileFromRoute(){
        return  new File(this.getJarFolder()+File.separatorChar+"config"+File.separatorChar+"Config.conf");
    }
    
    private FileInputStream getFileFromRouteDeveloper(){
        FileInputStream in = null;
        try {
            in =  new java.io.FileInputStream(new File("config").getAbsolutePath()+"\\Config.conf");
        } catch (FileNotFoundException ex) {
            java.util.logging.Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        }
        return in;
    }
    
    private String getJarFolder() {
        String path = PANEL.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        String decodedPath = path;
        try {
            decodedPath = URLDecoder.decode(path, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            log.error(ex);         
        }
        String Ruta = decodedPath.substring(0, decodedPath.lastIndexOf("/"));
        System.out.println("Path: "+Ruta);
        return Ruta;
        
  }
    
    
    public Map MapearPersistencia () throws IOException{
        FileInputStream in = null;
        Map con = new HashMap();
        try {
            Properties prop = new Properties();           
            in = this.getFileFromRouteDeveloper();
            //in = new java.io.FileInputStream(this.getFileFromRoute());
            
            if (in != null) {
                prop.load(in);
                if (prop != null) {                   
                    
                    Conexion.host_ip = Encrypt.DecryptBase64(prop.getProperty("servidor", "").trim());
                    Conexion.user = Encrypt.DecryptBase64(prop.getProperty("usuario", "").trim());
                    Conexion.pass = Encrypt.DecryptBase64(prop.getProperty("password", "").trim());  
                    Conexion.bd = Encrypt.DecryptBase64(prop.getProperty("base", "").trim());
                    
                    String server = "jdbc:mysql://"+Conexion.host_ip+ "/"+Conexion.bd;                    
                    con.put("javax.persistence.jdbc.url", server);
                    con.put("javax.persistence.jdbc.password", Conexion.pass);
                    con.put("javax.persistence.jdbc.user", Conexion.user);
                }
            }
            
        } catch (Exception e) {  
            log.error(e);
            System.out.println(e.getMessage());
        }       
        return con;
    }
}
